# -*- coding: utf-8 -*-
import hashlib
import json

import requests
from django.conf import settings

from common.chase import db as chase_db
from common.chase.model import CHASE_ORDER_STATUS
from common.mch import db as mch_db
from common.mch.model import MCH_TYPE
from common.utils import track_logging
from common.utils.exceptions import ParamError, AuthenticateError

_LOGGER = track_logging.getLogger(__name__)

_HANDLER_DCT = {
    MCH_TYPE.LOKI: settings.CHASE_API_LOKI,
    MCH_TYPE.WITCH: settings.CHASE_API_WITCH,
    MCH_TYPE.KS: settings.CHASE_API_DWC,
    MCH_TYPE.ZS: settings.CHASE_API_ZS,
    MCH_TYPE.TT: settings.CHASE_API_TT,
}


def _generate_sign(mch_id, params):
    mch_account = mch_db.get_account(mch_id)
    if not mch_account:
        raise AuthenticateError('mch_id invalid')
    s = ''
    for k in sorted(params.keys()):
        s += '%s=%s&' % (k, params[k])
    s += 'key=%s' % mch_account.api_key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def create_chase_order(params):
    mch_id = int(params["mch_id"])
    chase_id = params['chase_id']
    params['sign'] = _generate_sign(mch_id, params)
    _LOGGER.info("chase_order create params: %s", params)
    headers = {'Content-Type': 'application/json'}
    response = requests.post(_HANDLER_DCT.get(mch_id), data=json.dumps(params), headers=headers, timeout=10)
    _LOGGER.info("chase_order resp data: %s", response.text)

    try:
        response.raise_for_status()
    except (requests.exceptions.HTTPError, requests.exceptions.Timeout) as e:
        _LOGGER.warn('chase_charge status_code: %s, err_msg: %s', e.response.status_code, e.response.text)
        chase_db.update_order(chase_id, CHASE_ORDER_STATUS.FAIL)
        raise ParamError(e.response.text)

    data = json.loads(response.text)['data']
    status, msg = str(data['status']), data['msg']

    # status 0: 失败, 1: 成功, 2: 重复订单
    if status == '0':
        _LOGGER.info('chase_order error msg: %s, params: %s', msg, params)
        chase_db.update_order(chase_id, CHASE_ORDER_STATUS.FAIL)
        raise ParamError('chase_order error msg: %s' % msg)
    elif status == '2':
        chase_db.update_order(chase_id, CHASE_ORDER_STATUS.PROCESSED)
        raise ParamError(u'定单号已重复')
